﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Net;
using System.Net.Sockets;

namespace FinPlusConnMessage
{
    internal class Connection : IDisposable
    {
        public UdpClient Client = new UdpClient();
        public IPEndPoint Endpoint;
        public IPAddress Multicastaddress;

        //construct
        public Connection(string address, int port)
        {
            Multicastaddress = IPAddress.Parse(address);
            Client.ExclusiveAddressUse = false;
            Endpoint = new IPEndPoint(Multicastaddress, port);
            Client.JoinMulticastGroup(Multicastaddress);
        }

        public Connection(string address, int port, IPAddress endPoint)
        {
            Multicastaddress = IPAddress.Parse(address);
            Client.ExclusiveAddressUse = false;
            Endpoint = new IPEndPoint(endPoint ?? IPAddress.Any, port);
            Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            Client.ExclusiveAddressUse = false;
            Client.Client.Bind(Endpoint);
            Client.JoinMulticastGroup(Multicastaddress);
        }

        //public
        public void Dispose()
        {
            if (Client != null)
                Client.Close();
        }
    }
}
